﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using SharedGenomics.Core;
using SharedGenomics.Domain;
using SharedGenomics.Workbench.Core;
using SharedGenomics.Workbench.PresentationModel;

namespace SharedGenomics.Workbench.Views.WindowsForms
{
    public partial class JobSubmissionView : View, IJobSubmissionView
    {
        private JobSubmissionPTO _pto;

        public JobSubmissionView()
        {
            InitializeComponent();
            this.dgvCategoryFilters.ColumnHeadersDefaultCellStyle = this.dgvDatasets.ColumnHeadersDefaultCellStyle;
            this.dgvCategoryFilters.DefaultCellStyle = this.dgvDatasets.DefaultCellStyle;

            //prevent selection on category filter grid
            this.dgvCategoryFilters.SelectionChanged += (o, e) => { this.dgvCategoryFilters.ClearSelection(); };

            //handle format event on binding for the data set summary distribution type text box
            this.txtDistributionType.DataBindings["Text"].Format += new ConvertEventHandler(this.DistributionTypeText_Format);

            //add 'pass through' handlers which raise view events in response to widget events on this form
            this.Load += (o, e) => { this.Loaded.Raise(this); };
            this.dataSetsBindingSource.CurrentChanged += (o, e) =>
            {
                this.PTO.SelectedDataSetId = this.SelectedDataSetSummary == null ? (int?)null : this.SelectedDataSetSummary.Id;
                this.SelectedDataSetSummaryChanged.Raise(this);
            };

            this.btRefreshDataSets.Click += (o, e) => { this.RefreshDataSetsClicked.Raise(this); };
            this.btSubmit.Click += (o, e) => { this.SubmitClicked.Raise(this); };
        }

        private void DistributionTypeText_Format(object sender, ConvertEventArgs e)
        {
            if (e.DesiredType == typeof(string) && e.Value is bool)
            {
                bool isBinaryPhenotype = (bool)e.Value;
                e.Value = isBinaryPhenotype ? "Binary" : "Continuous";
            }
        }

        protected override IEnumerable<Binding> ValidatedDataBindings
        {
            get { return this.bindingSource.CurrencyManager.Bindings.Cast<Binding>(); }
        }

        public event EventHandler Loaded;
        public event EventHandler SubmitClicked;
        public event EventHandler RefreshDataSetsClicked;
        public event EventHandler SelectedDataSetSummaryChanged;

        public bool IsSubmitEnabled
        {
            set { this.btSubmit.Enabled = value; }
        }

        public JobSubmissionPTO PTO
        {
            private get { return this._pto; }
            set
            {
                this._pto = value;
                value.PropertyChanged += new PropertyChangedEventHandler(PTO_PropertyChanged);
                this.bindingSource.DataSource = value;
                this.jobTypesBindingSource.DataSource = value.JobTypes;
                this.cmbPermutationCount.DataSource = value.AvailablePermutationCounts;
                this.phenotypesBindingSource.DataSource = value.Phenotypes;
            }
        }

        private void PTO_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            var pto = (JobSubmissionPTO)sender;

            switch (e.PropertyName)
            {
                case "JobTypes":
                    this.jobTypesBindingSource.DataSource = pto.JobTypes;
                    break;

                case "AvailablePermutationCounts":
                    this.cmbPermutationCount.DataSource = pto.AvailablePermutationCounts;
                    break;

                case "Phenotypes":
                    this.phenotypesBindingSource.DataSource = pto.Phenotypes;
                    break;

                default:
                    break;
            }
        }

        public IEnumerable<DataSetSummary> DataSets
        {
            set { this.dataSetsBindingSource.DataSource = value; }
        }

        public DataSetSummary SelectedDataSetSummary
        {
            get { return this.dataSetsBindingSource.Current as DataSetSummary; }
        }

        public IEnumerable<ValueDisplayItem<string>> CategoryFilters
        {
            set { this.categoryFiltersBindingSource.DataSource = value; }
        }

        public IEnumerable<ValueDisplayItem<string>> Phenotypes
        {
            set { this.phenotypesBindingSource.DataSource = value; }
        }

        public bool IsSubmitProgressBarVisible
        {
            set { this.pgbSubmit.Visible = value; }
        }

        public string SubmitMessage
        {
            set { this.txtSubmitMessage.Text = value ?? String.Empty; }
        }

        private void dgvDatasets_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            //if (e.RowIndex.IsBetween(0, this.dgvDatasets.Rows.Count - 1, true) && e.ColumnIndex == 2)
            //{
            //    //if the row index is in range and the delete button column is being drawn
            //    //get the button cell being drawn
            //    DataGridViewButtonCell buttonCell = (DataGridViewButtonCell)this.dgvDatasets[2, e.RowIndex];
            //    IntPtr iconHandle = SharedGenomics.Workbench.Views.WindowsForms.Properties.Resources.DeleteHS.GetHicon();
            //    Icon icon = Icon.FromHandle(iconHandle);

            //    e.Paint(e.CellBounds, DataGridViewPaintParts.All);
            //    e.Graphics.DrawIcon(icon, e.CellBounds.Left + 3, e.CellBounds.Top + 3);
            //    e.Handled = true;
            //}
        }

        public IView JobOptionsView
        {
            set
            {
                Control view = value as Control;
                view.ThrowIfNull<ArgumentException>("Options view must be a System.Windows.Forms.Control");

                this.plJobOptions.Controls.Clear();
                //view.Dock = DockStyle.Fill;
                this.plJobOptions.Controls.Add(view);
            }
        }
    }
}
